import { ref } from 'vue'
import type { Position, GameState } from '../types/chess'

interface MoveResult {
  needsPromotion: boolean
  color: 'white' | 'black'
}

export function useChessGame(gameState: GameState) {
  const board = ref<(string | null)[][]>([])
  const selectedPiece = ref<Position | null>(null)
  const validMoves = ref<Position[]>([])
  const currentPlayer = ref<'white' | 'black'>('white')
  const isCheck = ref(false)
  const isCheckmate = ref(false)
  const lastMove = ref<{from: Position, to: Position} | null>(null)

  // 初始化棋盘
  const initializeBoard = () => {
    board.value = [
      ['black-rook', 'black-knight', 'black-bishop', 'black-queen', 'black-king', 'black-bishop', 'black-knight', 'black-rook'],
      ['black-pawn', 'black-pawn', 'black-pawn', 'black-pawn', 'black-pawn', 'black-pawn', 'black-pawn', 'black-pawn'],
      Array(8).fill(null),
      Array(8).fill(null),
      Array(8).fill(null),
      Array(8).fill(null),
      ['white-pawn', 'white-pawn', 'white-pawn', 'white-pawn', 'white-pawn', 'white-pawn', 'white-pawn', 'white-pawn'],
      ['white-rook', 'white-knight', 'white-bishop', 'white-queen', 'white-king', 'white-bishop', 'white-knight', 'white-rook']
    ]
  }

  const getPiece = (row: number, col: number): string | null => {
    if (row < 0 || row >= 8 || col < 0 || col >= 8) return null
    return board.value[row][col]
  }

  const isValidMove = (row: number, col: number): boolean => {
    return validMoves.value.some(move => 
      move.row === row && move.col === col
    )
  }

  const selectPiece = (row: number, col: number) => {
    // 如果已经将死，不允许继续移动
    if (isCheckmate.value) {
      selectedPiece.value = null
      validMoves.value = []
      return
    }
    
    const piece = board.value[row][col]
    
    // 如果点击的是已选中的棋子,则取消选择
    if (selectedPiece.value?.row === row && selectedPiece.value?.col === col) {
      selectedPiece.value = null
      validMoves.value = []
      return
    }
    
    // 选择新棋子
    if (piece && piece.includes(currentPlayer.value)) {
      selectedPiece.value = { row, col }
      validMoves.value = calculateValidMoves(row, col)
    } else {
      selectedPiece.value = null
      validMoves.value = []
    }
  }

  // 1. 找到王的位置
  const findKing = (color: string, testBoard: (string | null)[][]): Position | null => {
    for (let row = 0; row < 8; row++) {
      for (let col = 0; col < 8; col++) {
        if (testBoard[row][col] === `${color}-king`) {
          return { row, col }
        }
      }
    }
    return null
  }

  // 2. 检查是否可以攻击到某个格子
  const canPieceAttackSquare = (
    fromRow: number,
    fromCol: number,
    toRow: number,
    toCol: number,
    piece: string,
    testBoard: (string | null)[][]
  ): boolean => {
    const [color, type] = piece.split('-')
    
    // 检查路径上是否有其他棋子（除了马以外的棋子都需要检查）
    const isPathClear = (startRow: number, startCol: number, endRow: number, endCol: number): boolean => {
      const rowStep = endRow > startRow ? 1 : endRow < startRow ? -1 : 0
      const colStep = endCol > startCol ? 1 : endCol < startCol ? -1 : 0
      
      let currentRow = startRow + rowStep
      let currentCol = startCol + colStep
      
      while (currentRow !== endRow || currentCol !== endCol) {
        if (testBoard[currentRow][currentCol]) return false
        currentRow += rowStep
        currentCol += colStep
      }
      return true
    }

    switch (type) {
      case 'pawn': {
        const direction = color === 'white' ? -1 : 1
        return toRow === fromRow + direction && Math.abs(toCol - fromCol) === 1
      }
      
      case 'knight': {
        const rowDiff = Math.abs(toRow - fromRow)
        const colDiff = Math.abs(toCol - fromCol)
        return (rowDiff === 2 && colDiff === 1) || (rowDiff === 1 && colDiff === 2)
      }
      
      case 'bishop': {
        const rowDiff = Math.abs(toRow - fromRow)
        const colDiff = Math.abs(toCol - fromCol)
        if (rowDiff !== colDiff) return false
        return isPathClear(fromRow, fromCol, toRow, toCol)
      }
      
      case 'rook': {
        if (fromRow !== toRow && fromCol !== toCol) return false
        return isPathClear(fromRow, fromCol, toRow, toCol)
      }
      
      case 'queen': {
        const rowDiff = Math.abs(toRow - fromRow)
        const colDiff = Math.abs(toCol - fromCol)
        if (rowDiff !== colDiff && fromRow !== toRow && fromCol !== toCol) return false
        return isPathClear(fromRow, fromCol, toRow, toCol)
      }
      
      case 'king': {
        const rowDiff = Math.abs(toRow - fromRow)
        const colDiff = Math.abs(toCol - fromCol)
        return rowDiff <= 1 && colDiff <= 1
      }
    }
    
    return false
  }

  // 3. 检查是否有任何棋子可以攻击到指定位置
  const canAnyPieceAttackSquare = (
    row: number,
    col: number,
    attackerColor: string,
    testBoard: (string | null)[][]
  ): boolean => {
    for (let r = 0; r < 8; r++) {
      for (let c = 0; c < 8; c++) {
        const piece = testBoard[r][c]
        if (piece?.startsWith(attackerColor)) {
          if (canPieceAttackSquare(r, c, row, col, piece, testBoard)) {
            return true
          }
        }
      }
    }
    return false
  }

  // 4. 检查移动是否会导致己方被将军
  const willMoveExposeKing = (
    fromRow: number,
    fromCol: number,
    toRow: number,
    toCol: number,
    testBoard = board.value
  ): boolean => {
    const piece = testBoard[fromRow][fromCol]
    if (!piece) return false

    const color = piece.startsWith('white') ? 'white' : 'black'
    
    // 创建测试棋盘
    const newBoard = testBoard.map(row => [...row])
    newBoard[toRow][toCol] = piece
    newBoard[fromRow][fromCol] = null

    // 检查移动后是否被将军
    return isKingInCheck(color, newBoard)
  }

  // 5. 修改将死判定
  const isCheckMate = (color: string): boolean => {
    // 如果没有被将军，就不可能将死
    if (!isKingInCheck(color)) return false

    // 检查所有可能的解救移动
    for (let row = 0; row < 8; row++) {
      for (let col = 0; col < 8; col++) {
        const piece = board.value[row][col]
        if (piece?.startsWith(color)) {
          // 获取这个棋子的所有基本移动
          const basicMoves = getBasicValidMoves(row, col)
          
          // 检查每个移动是否能解除将军
          for (const move of basicMoves) {
            // 创建测试棋盘
            const testBoard = board.value.map(row => [...row])
            
            // 在测试棋盘上执行移动
            testBoard[move.row][move.col] = piece
            testBoard[row][col] = null
            
            // 检查移动后是否仍然被将军
            if (!isKingInCheck(color, testBoard)) {
              return false // 找到一个可以解除将军的移动
            }
          }
        }
      }
    }
    
    // 没有找到任何可以解除将军的移动
    return true
  }

  // 6. 实现基本移动规则
  const getBasicValidMoves = (
    row: number,
    col: number,
    testBoard = board.value
  ): Position[] => {
    const piece = testBoard[row][col]
    if (!piece) return []

    const [color, type] = piece.split('-')
    const moves: Position[] = []

    // 检查位置是否在棋盘内且不被己方棋子占据
    const isValidPosition = (r: number, c: number): boolean => {
      if (r < 0 || r > 7 || c < 0 || c > 7) return false
      const targetPiece = testBoard[r][c]
      return !targetPiece || !targetPiece.startsWith(color)
    }

    // 添加有效移动
    const addMove = (r: number, c: number) => {
      if (isValidPosition(r, c)) {
        moves.push({ row: r, col: c })
      }
    }

    // 根据不同棋子类型计算基本移动
    switch (type) {
      case 'pawn': {
        const direction = color === 'white' ? -1 : 1
        const startRow = color === 'white' ? 6 : 1

        // 前进一格
        if (!testBoard[row + direction]?.[col]) {
          addMove(row + direction, col)
          
          // 第一次移动可以前进两格
          if (row === startRow && !testBoard[row + direction * 2]?.[col]) {
            addMove(row + direction * 2, col)
          }
        }

        // 吃子移动
        for (const offset of [-1, 1]) {
          const newCol = col + offset
          if (newCol >= 0 && newCol < 8) {
            const targetPiece = testBoard[row + direction]?.[newCol]
            if (targetPiece && targetPiece.startsWith(color === 'white' ? 'black' : 'white')) {
              addMove(row + direction, newCol)
            }
          }
        }
        break
      }

      case 'knight': {
        const knightMoves = [
          [-2, -1], [-2, 1], [-1, -2], [-1, 2],
          [1, -2], [1, 2], [2, -1], [2, 1]
        ]
        for (const [dr, dc] of knightMoves) {
          addMove(row + dr, col + dc)
        }
        break
      }

      case 'bishop': {
        const directions = [[-1, -1], [-1, 1], [1, -1], [1, 1]]
        for (const [dr, dc] of directions) {
          let r = row + dr
          let c = col + dc
          while (r >= 0 && r < 8 && c >= 0 && c < 8) {
            addMove(r, c)
            if (testBoard[r][c]) break // 遇到棋子就停止
            r += dr
            c += dc
          }
        }
        break
      }

      case 'rook': {
        const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
        for (const [dr, dc] of directions) {
          let r = row + dr
          let c = col + dc
          while (r >= 0 && r < 8 && c >= 0 && c < 8) {
            addMove(r, c)
            if (testBoard[r][c]) break // 遇到棋子就停止
            r += dr
            c += dc
          }
        }
        break
      }

      case 'queen': {
        const directions = [
          [-1, -1], [-1, 0], [-1, 1],
          [0, -1],          [0, 1],
          [1, -1],  [1, 0],  [1, 1]
        ]
        for (const [dr, dc] of directions) {
          let r = row + dr
          let c = col + dc
          while (r >= 0 && r < 8 && c >= 0 && c < 8) {
            addMove(r, c)
            if (testBoard[r][c]) break // 遇到棋子就停止
            r += dr
            c += dc
          }
        }
        break
      }

      case 'king': {
        const kingMoves = [
          [-1, -1], [-1, 0], [-1, 1],
          [0, -1],          [0, 1],
          [1, -1],  [1, 0],  [1, 1]
        ]
        for (const [dr, dc] of kingMoves) {
          addMove(row + dr, col + dc)
        }
        break
      }
    }

    return moves
  }

  // 3. 将军检查使用独立的简化逻辑
  const isKingInCheck = (color: string, testBoard = board.value): boolean => {
    // 找到王的位
    const kingPos = findKing(color, testBoard)
    if (!kingPos) return false

    // 检查对方所有棋子是否可以攻击到王
    const opponentColor = color === 'white' ? 'black' : 'white'
    for (let row = 0; row < 8; row++) {
      for (let col = 0; col < 8; col++) {
        const piece = testBoard[row][col]
        if (piece?.startsWith(opponentColor)) {
          if (canPieceAttackSquare(row, col, kingPos.row, kingPos.col, piece, testBoard)) {
            return true
          }
        }
      }
    }
    return false
  }

  // 2. 完整的移动检查，包含将军判定
  const calculateValidMoves = (
    row: number,
    col: number,
    testBoard = board.value
  ): Position[] => {
    const piece = testBoard[row][col]
    if (!piece) return []

    // 如果已经将死，返回空数组
    if (isCheckmate.value) return []

    // 获取所有基本移动
    const basicMoves = getBasicValidMoves(row, col, testBoard)
    const validMoves: Position[] = []

    // 检查每个基本移动是否会导致己方被将军
    for (const move of basicMoves) {
      // 创建测试棋盘
      const newBoard = testBoard.map(row => [...row])
      newBoard[move.row][move.col] = piece
      newBoard[row][col] = null

      // 如果这个移动不会导致己方被将军，就添加它
      if (!willMoveExposeKing(row, col, move.row, move.col, newBoard)) {
        validMoves.push(move)
      }
    }

    return validMoves
  }

  // 5. 移动执行逻辑优化
  const movePiece = (toRow: number, toCol: number): MoveResult | null => {
    if (!selectedPiece.value || !isValidMove(toRow, toCol)) return null

    const fromRow = selectedPiece.value.row
    const fromCol = selectedPiece.value.col
    const piece = board.value[fromRow][fromCol]
    
    if (!piece) return null

    // 记录这步棋
    lastMove.value = {
      from: { row: fromRow, col: fromCol },
      to: { row: toRow, col: toCol }
    }

    // 记录被吃的棋子
    const capturedPiece = board.value[toRow][toCol]
    if (capturedPiece) {
      gameState.addCapture(capturedPiece)
    }

    // 执行移动
    board.value[toRow][toCol] = piece
    board.value[fromRow][fromCol] = null

    // 检查是否需要升变
    const needsPromotion = piece.includes('pawn') && (toRow === 0 || toRow === 7)

    // 检查是否将军
    const nextPlayer = currentPlayer.value === 'white' ? 'black' : 'white'
    isCheck.value = isKingInCheck(nextPlayer)

    // 检查是否将死
    if (isCheck.value) {
      isCheckmate.value = isCheckMate(nextPlayer)
      if (isCheckmate.value) {
        setTimeout(() => {
          alert(`${currentPlayer.value === 'white' ? '白方' : '黑方'}获胜！`)
        }, 100)
      }
    }

    // 切换玩家
    currentPlayer.value = nextPlayer

    // 清除选择和有效移动
    validMoves.value = []
    selectedPiece.value = null

    return {
      needsPromotion,
      color: piece.includes('white') ? 'white' : 'black'
    }
  }

  // 初始化棋盘
  initializeBoard()

  return {
    board,
    selectedPiece,
    validMoves,
    getPiece,
    isValidMove,
    selectPiece,
    movePiece,
    isCheck,
    isCheckmate,
    calculateValidMoves,
    currentPlayer,
    lastMove,
  }
} 